<template>
  <div>
    <div class="user-info" v-if="user && !isUploading">
      <img :src="getCreatorAvatarUrl(user.avatar)" alt="User Avatar" class="user-avatar" />
      <p><strong>昵称:</strong> {{ user.nickname }}</p>
      <p><strong>用户ID:</strong> {{ user.id }}</p>
      <button type="button" @click="showUploadForm">上传文章</button>
    </div>
    <div v-else-if="isUploading" class="upload-form">
      <div>
        <label for="stem">文章摘要:</label>
        <input type="text" id="stem" v-model="articleStem" placeholder="请输入文章摘要" />
      </div>
      <div>
        <label for="content">文章内容:</label>
        <textarea id="content" v-model="articleContent" placeholder="请输入文章内容"></textarea>
      </div>
      <button type="button" @click="uploadArticle">提交</button>
      <button type="button" @click="cancelUpload">取消</button>
    </div>
    <div v-else>
      <p>加载中...</p>
    </div>

    <div class="article-page" v-if="!isUploading">
      <div
        v-for="item in articles"
        :key="item.id"
        @click="$router.push(`/detail/${item.id}`)"
        class="article-item">
        <div class="head">
          <img :src="getCreatorAvatarUrl(item.creatorAvatar)" alt="" />
          <div class="con">
            <p class="title">{{ item.stem }}</p>
            <p class="other">{{ item.creatorName }} | {{ item.createdAt }}</p>
          </div>
        </div>
        <div class="body">
          {{ item.content }}
        </div>
        <div class="foot">
          点赞 {{ item.likeCount }} | 浏览 {{ item.views }} | 评论 {{ item.commentCount }}
          <button class="like-button" @click.stop="toggleFavorite(item)">
            {{ isFavorited(item.id) ? '已收藏' : '收藏' }}
          </button>
          <button class="delete-button" @click.stop="confirmDeleteArticle(item.id)">
            删除
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import '@/styles/articleStyles.less'; // 引入样式文件
import '@/styles/userStyles.less'; 

export default {
  name: 'UserPage',
  data() {
    return {
      user: null,
      articles: [],
      articleStem: '',
      articleContent: '',
      favoriteArticles: [],
      isUploading: false,
      userId: localStorage.getItem('userId')
    };
  },
  async created() {
    this.fetchUserData(); // 获取用户数据
    await this.getFavoriteArticles(); // 先获取收藏文章
    this.fetchArticles(); // 获取该用户的文章
  },
  methods: {
    async fetchUserData() {
      try {
        const userId = localStorage.getItem('userId');
        console.log('当前用户ID:', userId);
        if (!userId) {
          throw new Error('用户ID未找到');
        }

        const response = await axios.get(`http://localhost:8000/getuserbyid?id=${userId}`);
        this.user = response.data;
      } catch (error) {
        console.error('获取用户信息失败:', error);
        alert('获取用户信息失败，请重试。');
      }
    },
    
    getCreatorAvatarUrl(avatarPath) {
      if (avatarPath.startsWith('data:')) {
        return avatarPath;
      }

      if (avatarPath.startsWith('http://localhost:5000/')) {
        avatarPath = avatarPath.replace('http://localhost:5000/', '');
      }

      if (!avatarPath.startsWith('http')) {
        avatarPath = require(`@/assets/upload/${avatarPath}`);
      }

      return avatarPath;
    },

    async fetchArticles() {
      try {
        const userId = localStorage.getItem('userId');
        if (!userId) {
          throw new Error('用户ID未找到');
        }

        const res = await axios.get(`http://localhost:8000/getArticlesByUserId/${userId}`);
        this.articles = res.data; // 确保 API 返回的数据结构正确
        console.log('用户文章:', this.articles);
      } catch (error) {
        console.error('获取用户文章失败:', error);
      }
    },

    async getFavoriteArticles() {
      try {
        const res = await axios.get(`http://localhost:8000/getArticleFavorites/${this.userId}`);
        this.favoriteArticles = res.data.map(favorite => String(favorite.articleId)); // 确保 ID 是字符串类型
        console.log('收藏的文章ID:', this.favoriteArticles);
      } catch (error) {
        console.error('获取收藏文章失败:', error);
      }
    },

    isFavorited(articleId) {
      return this.favoriteArticles.includes(String(articleId)); // 确保 ID 是字符串类型
    },

    async toggleFavorite(item) {
      console.log(`收藏按钮被点击，文章ID: ${item.id}`);
      console.log(`用户ID: ${this.userId}`);

      if (this.isFavorited(item.id)) {
        // 取消收藏
        try {
          await axios.delete(`http://localhost:8000/delete-favorite?userId=${this.userId}&articleId=${item.id}`);
          this.favoriteArticles = this.favoriteArticles.filter(id => id !== String(item.id));
          alert('取消收藏成功');
        } catch (error) {
          console.error('取消收藏失败:', error);
          alert('取消收藏失败');
        }
      } else {
        // 收藏
        try {
          await axios.post('http://localhost:8000/addArticleFavorite', {
            userId: this.userId,
            articleId: item.id
          });
          this.favoriteArticles.push(String(item.id));
          alert('收藏成功');
        } catch (error) {
          alert('收藏失败');
          console.error('收藏失败:', error);
        }
      }
    },
    
    showUploadForm() {
      this.isUploading = true;
    },
    async uploadArticle() {
      const articleData = {
        creatorAvatar: this.user.avatar,
        stem: this.articleStem,
        creatorName: this.user.nickname,
        createdAt: new Date().toISOString().split('T')[0],
        content: this.articleContent,
        likeCount: '0',
        views: '0',
        userId: this.userId
      };

      try {
        const response = await axios.post('http://localhost:8000/addArticle', articleData);
        console.log('文章上传成功:', response.data);
        alert('文章上传成功');
        this.articleStem = '';
        this.articleContent = '';
        this.isUploading = false;
        this.fetchArticles(); // 刷新文章列表
      } catch (error) {
        console.error('文章上传失败:', error);
        alert('文章上传失败，请重试。');
      }
    },
    
    cancelUpload() {
      this.isUploading = false;
      this.articleStem = '';
      this.articleContent = '';
    },

    confirmDeleteArticle(articleId) {
      if (confirm('确定要删除这篇文章吗？')) {
        this.deleteArticle(articleId);
      }
    },

    async deleteArticle(articleId) {
      try {
        console.log(`删除按钮被点击，文章ID: ${articleId}`);
        // 发送删除请求
        const response = await axios.delete(`http://localhost:8000/deleteArticle/${articleId}`);
        console.log('删除成功', response.data);

        // 从本地数据中移除已删除的文章
        this.articles = this.articles.filter(article => article.id !== articleId);
        alert('文章删除成功');
      } catch (error) {
        console.error('删除失败', error);
        alert('文章删除失败，请重试。');
      }
    }
  }
};
</script>

<style scoped>
.delete-button {
  background-color: white;
  border: none;
  color: #999;
  padding: 5px 10px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 12px;
  cursor: pointer;
  border-radius: 4px;
}

.delete-button {
  color: red;
}

.upload-form {
  margin-top: 20px;
  margin-left: 20px;
}

.upload-form label {
  display: block;
  margin-bottom: 5px;
}

.upload-form input {
  width: 70%;
  padding: 8px;
  margin-bottom: 10px;
  box-sizing: border-box;
}

.upload-form textarea {
  width: 90%;
  height: 350px;
  padding: 16px;
  margin-bottom: 10px;
  box-sizing: border-box;
  font-size: 16px;
}

.upload-form button {
  padding: 8px 16px;
  margin-right: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  cursor: pointer;
}

.upload-form button:hover {
  background-color: #0056b3;
}
</style>